package org.lsy.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.lsy.service.UserService;
import org.lsy.service.ValidateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author liusy95
 * @version 1.0
 * @date 2020/7/31
 */
@Component
@Slf4j
public class ValidateFilter implements GlobalFilter, Ordered {

    @Autowired
    private ValidateService validateService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/api/user/info", request.getPath().toString());
        if (match) {
                boolean valid = validateService.validateToken(exchange.getRequest());
                if (!valid){
                    response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    String data = "您尚未授权";
                    DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                    return response.writeWith(Mono.just(wrap));
                }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }


}
